<template>
  <div class="vip-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>VIP管理</h2>
      <p>管理VIP会员用户和套餐配置</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon vip-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalVipUsers }}</div>
                <div class="stat-label">VIP用户总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.activeVipUsers }}</div>
                <div class="stat-label">活跃VIP用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon revenue-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ stats.monthlyRevenue }}</div>
                <div class="stat-label">本月收入</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon conversion-icon">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.conversionRate }}%</div>
                <div class="stat-label">转化率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能标签页 -->
    <el-card class="main-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- VIP用户列表 -->
        <el-tab-pane label="VIP用户" name="users">
          <div class="tab-content">
            <!-- 搜索和筛选 -->
            <div class="search-bar">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-input
                    v-model="userFilters.keyword"
                    placeholder="搜索用户ID、昵称或手机号"
                    clearable
                    @clear="loadVipUsers"
                    @keyup.enter="loadVipUsers"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="userFilters.status"
                    placeholder="VIP状态"
                    clearable
                    @change="loadVipUsers"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="正常" value="active" />
                    <el-option label="过期" value="expired" />
                    <el-option label="即将过期" value="expiring" />
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="userFilters.level"
                    placeholder="VIP等级"
                    clearable
                    @change="loadVipUsers"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="VIP1" value="1" />
                    <el-option label="VIP2" value="2" />
                    <el-option label="VIP3" value="3" />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="loadVipUsers">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetUserFilters">重置</el-button>
                </el-col>
              </el-row>
            </div>

            <!-- VIP用户表格 -->
            <el-table
              :data="vipUsers"
              v-loading="usersLoading"
              style="width: 100%"
              @selection-change="handleUserSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="用户ID" width="80" />
              <el-table-column prop="nickname" label="用户昵称" width="120">
                <template #default="{ row }">
                  <div class="user-info">
                    <el-avatar :size="32" :src="row.avatar || '/touxiang.png'" />
                    <span class="nickname">{{ row.nickname || '未设置' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号" width="120" />
              <el-table-column prop="vipLevel" label="VIP等级" width="100">
                <template #default="{ row }">
                  <el-tag :type="getVipLevelType(row.vipLevel)">
                    VIP{{ row.vipLevel }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="vipStartTime" label="开通时间" width="120" />
              <el-table-column prop="vipEndTime" label="到期时间" width="120">
                <template #default="{ row }">
                  <span :class="{ 'expiring-text': isExpiring(row.vipEndTime) }">
                    {{ row.vipEndTime }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getVipStatusType(row.status)">
                    {{ getVipStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="totalSpent" label="累计消费" width="100">
                <template #default="{ row }">
                  ¥{{ row.totalSpent || 0 }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="viewUserDetail(row)">
                    详情
                  </el-button>
                  <el-button size="small" type="warning" @click="extendVip(row)">
                    续期
                  </el-button>
                  <el-button size="small" type="danger" @click="cancelVip(row)">
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="userPagination.current"
                v-model:page-size="userPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="userPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="loadVipUsers"
                @current-change="loadVipUsers"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- VIP套餐管理 -->
        <el-tab-pane label="VIP套餐" name="packages">
          <div class="tab-content">
            <div class="toolbar">
              <el-button type="primary" @click="addVipPackage">
                <el-icon><Plus /></el-icon>
                新增套餐
              </el-button>
            </div>

            <!-- VIP套餐表格 -->
            <el-table :data="vipPackages" v-loading="packagesLoading" style="width: 100%">
              <el-table-column prop="id" label="套餐ID" width="80" />
              <el-table-column prop="name" label="套餐名称" width="150" />
              <el-table-column prop="type" label="套餐类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.type === 'daily' ? 'primary' : 'success'">
                    {{ row.type === 'daily' ? '日卡' : '月卡' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="时长" width="100">
                <template #default="{ row }">
                  {{ row.duration }}{{ row.type === 'daily' ? '天' : '天' }}
                </template>
              </el-table-column>
              <el-table-column prop="originalPrice" label="原价" width="100">
                <template #default="{ row }">
                  ¥{{ row.originalPrice }}
                </template>
              </el-table-column>
              <el-table-column prop="price" label="现价" width="100">
                <template #default="{ row }">
                  ¥{{ row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="description" label="套餐描述" min-width="200">
                <template #default="{ row }">
                  <span>{{ row.description }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="recommended" label="推荐" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.recommended ? 'warning' : 'info'">
                    {{ row.recommended ? '推荐' : '普通' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="editVipPackage(row)">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="handleDeleteVipPackage(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- VIP订单 -->
        <el-tab-pane label="VIP订单" name="orders">
          <div class="tab-content">
            <!-- 订单搜索 -->
            <div class="search-bar">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-input
                    v-model="orderFilters.keyword"
                    placeholder="搜索订单号或用户"
                    clearable
                    @clear="loadVipOrders"
                    @keyup.enter="loadVipOrders"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="orderFilters.status"
                    placeholder="订单状态"
                    clearable
                    @change="loadVipOrders"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="待支付" value="pending" />
                    <el-option label="已支付" value="paid" />
                    <el-option label="已取消" value="cancelled" />
                    <el-option label="已退款" value="refunded" />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="loadVipOrders">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetOrderFilters">重置</el-button>
                </el-col>
              </el-row>
            </div>

            <!-- VIP订单表格 -->
            <el-table :data="vipOrders" v-loading="ordersLoading" style="width: 100%">
              <el-table-column prop="orderNo" label="订单号" width="180" />
              <el-table-column prop="userId" label="用户ID" width="80" />
              <el-table-column prop="userNickname" label="用户昵称" width="120" />
              <el-table-column prop="packageName" label="套餐名称" width="150" />
              <el-table-column prop="amount" label="金额" width="100">
                <template #default="{ row }">
                  ¥{{ row.amount }}
                </template>
              </el-table-column>
              <el-table-column prop="paymentMethod" label="支付方式" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getOrderStatusType(row.status)">
                    {{ getOrderStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="150" />
              <el-table-column prop="payTime" label="支付时间" width="150" />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="viewOrderDetail(row)">
                    详情
                  </el-button>
                  <el-button
                    v-if="row.status === 'paid'"
                    size="small"
                    type="danger"
                    @click="refundOrder(row)"
                  >
                    退款
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="orderPagination.current"
                v-model:page-size="orderPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="orderPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="loadVipOrders"
                @current-change="loadVipOrders"
              />
      </div>
    </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增/编辑套餐对话框 -->
    <el-dialog
      v-model="packageDialogVisible"
      :title="isEditMode ? '编辑VIP套餐' : '新增VIP套餐'"
      width="600px"
      @close="handlePackageDialogClose"
    >
      <el-form
        ref="packageFormRef"
        :model="packageForm"
        :rules="packageFormRules"
        label-width="100px"
      >
        <el-form-item label="套餐类型" prop="type">
          <el-select
            v-model="packageForm.type"
            placeholder="请选择套餐类型"
            style="width: 100%"
            :disabled="isEditMode"
          >
            <el-option label="连续包日" value="daily" />
            <el-option label="连续包月" value="monthly" />
            <el-option label="连续包季" value="quarterly" />
            <el-option label="连续包年" value="yearly" />
          </el-select>
        </el-form-item>

        <el-form-item label="套餐名称" prop="name">
          <el-input
            v-model="packageForm.name"
            placeholder="请输入套餐名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="原价" prop="originalPrice">
          <el-input-number
            v-model="packageForm.originalPrice"
            :precision="2"
            :min="0.01"
            :max="9999.99"
            :step="0.01"
            placeholder="请输入原价"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="现价" prop="price">
          <el-input-number
            v-model="packageForm.price"
            :precision="2"
            :min="0.01"
            :max="9999.99"
            :step="0.01"
            placeholder="请输入现价"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="时长" prop="duration">
          <el-input-number
            v-model="packageForm.duration"
            :min="1"
            :max="3650"
            placeholder="请输入时长（天数）"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="套餐描述" prop="description">
          <el-input
            v-model="packageForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="推荐套餐">
          <el-switch
            v-model="packageForm.recommended"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="packageForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="packageDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="packageSubmitting" @click="handlePackageSubmit">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TabPaneName } from 'element-plus'
import { 
  getVipStats, 
  getVipUsers, 
  getVipPackages, 
  getVipOrders,
  extendVipUser,
  cancelUserVip,
  updateVipPackageStatus,
  deleteVipPackage,
  refundVipOrder,
  createVipPackage,
  updateVipPackage
} from '@/api'

// 响应式数据
const activeTab = ref('users')
const usersLoading = ref(false)
const packagesLoading = ref(false)
const ordersLoading = ref(false)

// 统计数据
const stats = reactive({
  totalVipUsers: 0,
  activeVipUsers: 0,
  monthlyRevenue: 0,
  conversionRate: 0
})

// VIP用户相关
const vipUsers = ref([])
const userFilters = reactive({
  keyword: '',
  status: '',
  level: ''
})
const userPagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// VIP套餐相关
const vipPackages = ref([])

// VIP订单相关
const vipOrders = ref([])
const orderFilters = reactive({
  keyword: '',
  status: ''
})
const orderPagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 套餐对话框相关
const packageDialogVisible = ref(false)
const isEditMode = ref(false)
const packageSubmitting = ref(false)
const packageFormRef = ref()

// 套餐表单数据
const packageForm = reactive({
  type: '',
  name: '',
  price: null,
  originalPrice: null,
  description: '',
  duration: null,
  recommended: false,
  status: 1
})

// 套餐表单验证规则
const packageFormRules = {
  type: [
    { required: true, message: '请选择套餐类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' },
    { min: 1, max: 50, message: '套餐名称长度在1-50个字符之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入现价', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 9999.99, message: '现价必须在0.01-9999.99之间', trigger: 'blur' }
  ],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 9999.99, message: '原价必须在0.01-9999.99之间', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入时长', trigger: 'blur' },
    { type: 'number', min: 1, max: 3650, message: '时长必须在1-3650天之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '套餐描述长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 当前编辑的套餐ID
const currentPackageId = ref<number | null>(null)

// 方法
const handleTabChange = (tabName: TabPaneName) => {
  switch (tabName) {
    case 'users':
      loadVipUsers()
      break
    case 'packages':
      loadVipPackages()
      break
    case 'orders':
      loadVipOrders()
      break
  }
}

const loadVipStats = async () => {
  try {
    const response = await getVipStats()
    if (response.success && response.data) {
      Object.assign(stats, response.data)
    } else {
      // 如果API返回失败，使用模拟数据
      stats.totalVipUsers = 1234
      stats.activeVipUsers = 1156
      stats.monthlyRevenue = 156800
      stats.conversionRate = 12.5
    }
  } catch (error) {
    console.error('加载VIP统计失败:', error)
    // API调用失败时使用模拟数据
    stats.totalVipUsers = 1234
    stats.activeVipUsers = 1156
    stats.monthlyRevenue = 156800
    stats.conversionRate = 12.5
  }
}

const loadVipUsers = async () => {
  usersLoading.value = true
  try {
    const params = {
      current: userPagination.current,
      size: userPagination.size,
      ...userFilters
    }
    
    const response = await getVipUsers(params)
    if (response.success && response.data) {
      vipUsers.value = response.data.data || []
      userPagination.total = response.data.total || 0
    } else {
      // API调用失败时使用模拟数据
      vipUsers.value = [
        {
          id: 1001,
          nickname: 'VIP用户1',
          phone: '138****1234',
          avatar: '',
          vipLevel: 2,
          vipStartTime: '2024-01-15',
          vipEndTime: '2024-07-15',
          status: 'active',
          totalSpent: 299
        },
        {
          id: 1002,
          nickname: 'VIP用户2',
          phone: '139****5678',
          avatar: '',
          vipLevel: 1,
          vipStartTime: '2024-02-01',
          vipEndTime: '2024-03-01',
          status: 'expired',
          totalSpent: 99
        }
      ]
      userPagination.total = 50
    }
  } catch (error) {
    console.error('加载VIP用户失败:', error)
    // API调用失败时使用模拟数据
    vipUsers.value = [
      {
        id: 1001,
        nickname: 'VIP用户1',
        phone: '138****1234',
        avatar: '',
        vipLevel: 2,
        vipStartTime: '2024-01-15',
        vipEndTime: '2024-07-15',
        status: 'active',
        totalSpent: 299
      }
    ]
    userPagination.total = 1
  } finally {
    usersLoading.value = false
  }
}

const loadVipPackages = async () => {
  packagesLoading.value = true
  try {
    console.log('正在加载VIP套餐...')
    const response = await getVipPackages()
    console.log('VIP套餐API响应:', response)
    
    if (response.success && response.data) {
      vipPackages.value = response.data || []
      console.log('VIP套餐数据:', vipPackages.value)
    } else {
      console.error('获取VIP套餐失败:', response)
      ElMessage.error('获取VIP套餐失败: ' + (response?.message || '未知错误'))
      vipPackages.value = []
    }
  } catch (error) {
    console.error('加载VIP套餐失败:', error)
    ElMessage.error('加载VIP套餐失败: ' + (error as Error).message)
    vipPackages.value = []
  } finally {
    packagesLoading.value = false
  }
}

const loadVipOrders = async () => {
  ordersLoading.value = true
  try {
    const params = {
      current: orderPagination.current,
      size: orderPagination.size,
      ...orderFilters
    }
    
    const response = await getVipOrders(params)
    if (response.success && response.data) {
      vipOrders.value = response.data.data || []
      orderPagination.total = response.data.total || 0
    } else {
      // API调用失败时使用模拟数据
      vipOrders.value = [
        {
          orderNo: 'VIP202401150001',
          userId: 1001,
          userNickname: 'VIP用户1',
          packageName: 'VIP月卡',
          amount: 99,
          paymentMethod: '微信支付',
          status: 'paid',
          createTime: '2024-01-15 10:30:00',
          payTime: '2024-01-15 10:31:00'
        }
      ]
      orderPagination.total = 25
    }
  } catch (error) {
    console.error('加载VIP订单失败:', error)
    // API调用失败时使用模拟数据
    vipOrders.value = [
      {
        orderNo: 'VIP202401150001',
        userId: 1001,
        userNickname: 'VIP用户1',
        packageName: 'VIP月卡',
        amount: 99,
        paymentMethod: '微信支付',
        status: 'paid',
        createTime: '2024-01-15 10:30:00',
        payTime: '2024-01-15 10:31:00'
      }
    ]
    orderPagination.total = 1
  } finally {
    ordersLoading.value = false
  }
}

// 工具方法
const getVipLevelType = (level: number) => {
  const types = { 1: '', 2: 'warning', 3: 'danger' }
  return types[level] || ''
}

const getVipStatusType = (status: string) => {
  const types = {
    active: 'success',
    expired: 'danger',
    expiring: 'warning'
  }
  return types[status] || 'info'
}

const getVipStatusText = (status: string) => {
  const texts = {
    active: '正常',
    expired: '已过期',
    expiring: '即将过期'
  }
  return texts[status] || '未知'
}

const getOrderStatusType = (status: string) => {
  const types = {
    pending: 'warning',
    paid: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return types[status] || 'info'
}

const getOrderStatusText = (status: string) => {
  const texts = {
    pending: '待支付',
    paid: '已支付',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || '未知'
}

const getDurationUnit = (type: string) => {
  const units = {
    day: '天',
    month: '个月',
    year: '年'
  }
  return units[type] || '天'
}

const isExpiring = (endTime: string) => {
  const end = new Date(endTime)
  const now = new Date()
  const diff = end.getTime() - now.getTime()
  const days = Math.ceil(diff / (1000 * 3600 * 24))
  return days <= 7 && days > 0
}

// 操作方法
const resetUserFilters = () => {
  Object.assign(userFilters, {
    keyword: '',
    status: '',
    level: ''
  })
  loadVipUsers()
}

const resetOrderFilters = () => {
  Object.assign(orderFilters, {
    keyword: '',
    status: ''
  })
  loadVipOrders()
}

const handleUserSelectionChange = (selection: any[]) => {
  console.log('选中的用户:', selection)
}

const viewUserDetail = (user: any) => {
  ElMessage.info(`查看用户 ${user.nickname} 的详情`)
}

const extendVip = async (user: any) => {
  try {
    await ElMessageBox.confirm(`确定要为用户 ${user.nickname} 续期VIP吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await extendVipUser(user.id, { duration: 30, durationType: 'day' })
    if (response.success) {
      ElMessage.success('VIP续期成功')
      loadVipUsers() // 重新加载用户列表
    } else {
      ElMessage.error(response.message || 'VIP续期失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('VIP续期失败:', error)
      ElMessage.error('VIP续期失败')
    }
  }
}

const cancelVip = async (user: any) => {
  try {
    await ElMessageBox.confirm(`确定要取消用户 ${user.nickname} 的VIP吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await cancelUserVip(user.id, { reason: '管理员操作取消' })
    if (response.success) {
      ElMessage.success('VIP取消成功')
      loadVipUsers() // 重新加载用户列表
    } else {
      ElMessage.error(response.message || 'VIP取消失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('VIP取消失败:', error)
      ElMessage.error('VIP取消失败')
    }
  }
}

const addVipPackage = () => {
  isEditMode.value = false
  currentPackageId.value = null
  resetPackageForm()
  packageDialogVisible.value = true
}

const editVipPackage = (pkg: any) => {
  isEditMode.value = true
  currentPackageId.value = pkg.id
  
  // 填充表单数据
  packageForm.type = pkg.type
  packageForm.name = pkg.name
  packageForm.price = pkg.price
  packageForm.originalPrice = pkg.originalPrice
  packageForm.description = pkg.description || ''
  packageForm.duration = pkg.duration
  packageForm.recommended = pkg.recommended || false
  packageForm.status = pkg.status || 1
  
  packageDialogVisible.value = true
}

// 重置套餐表单
const resetPackageForm = () => {
  Object.assign(packageForm, {
    type: '',
    name: '',
    price: null,
    originalPrice: null,
    description: '',
    duration: null,
    recommended: false,
    status: 1
  })
  packageFormRef.value?.clearValidate()
}

// 处理套餐对话框关闭
const handlePackageDialogClose = () => {
  resetPackageForm()
  packageDialogVisible.value = false
}

// 处理套餐表单提交
const handlePackageSubmit = async () => {
  if (!packageFormRef.value) return
  
  try {
    // 验证表单
    const valid = await packageFormRef.value.validate()
    if (!valid) return
    
    packageSubmitting.value = true
    
    // 准备提交数据
    const submitData = {
      type: packageForm.type,
      name: packageForm.name,
      price: Number(packageForm.price),
      originalPrice: Number(packageForm.originalPrice),
      description: packageForm.description,
      duration: Number(packageForm.duration),
      recommended: packageForm.recommended,
      status: packageForm.status
    }
    
    let response
    if (isEditMode.value && currentPackageId.value) {
      // 更新套餐
      console.log('更新套餐:', { id: currentPackageId.value, data: submitData })
      response = await updateVipPackage(currentPackageId.value, submitData)
    } else {
      // 创建套餐
      console.log('创建套餐:', submitData)
      response = await createVipPackage(submitData)
    }
    
    if (response.success) {
      const action = isEditMode.value ? '更新' : '创建'
      ElMessage.success(`${action}套餐成功`)
      packageDialogVisible.value = false
      resetPackageForm()
      
      // 重新加载套餐列表
      await loadVipPackages()
    } else {
      ElMessage.error(response.message || `${isEditMode.value ? '更新' : '创建'}套餐失败`)
    }
  } catch (error) {
    console.error('套餐表单提交失败:', error)
    ElMessage.error('操作失败: ' + (error as Error).message)
  } finally {
    packageSubmitting.value = false
  }
}

const handleDeleteVipPackage = async (pkg: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除套餐 ${pkg.name} 吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await deleteVipPackage(pkg.id)
    if (response.success) {
      ElMessage.success('套餐删除成功')
      loadVipPackages() // 重新加载套餐列表
    } else {
      ElMessage.error(response.message || '套餐删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('套餐删除失败:', error)
      ElMessage.error('套餐删除失败')
    }
  }
}

const updatePackageStatus = async (pkg: any) => {
  try {
    // 检查套餐ID是否有效
    if (!pkg.id) {
      ElMessage.error('套餐ID无效，无法更新状态')
      // 恢复状态
      pkg.status = pkg.status ? 0 : 1
      return
    }
    
    console.log('更新套餐状态:', { id: pkg.id, status: pkg.status, name: pkg.name })
    const response = await updateVipPackageStatus(pkg.id, pkg.status)
    if (response.success) {
      const status = pkg.status ? '启用' : '禁用'
      ElMessage.success(`套餐 ${pkg.name} ${status}成功`)
    } else {
      // 如果API调用失败，恢复状态
      pkg.status = pkg.status ? 0 : 1
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('更新套餐状态失败:', error)
    // 如果API调用失败，恢复状态
    pkg.status = pkg.status ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const viewOrderDetail = (order: any) => {
  ElMessage.info(`查看订单 ${order.orderNo} 的详情`)
}

const refundOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm(`确定要退款订单 ${order.orderNo} 吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await refundVipOrder(order.orderNo, { 
      reason: '管理员操作退款',
      amount: order.amount
    })
    if (response.success) {
      ElMessage.success('订单退款成功')
      loadVipOrders() // 重新加载订单列表
    } else {
      ElMessage.error(response.message || '订单退款失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('订单退款失败:', error)
      ElMessage.error('订单退款失败')
    }
  }
}

// 组件挂载
onMounted(() => {
  loadVipStats()
  loadVipUsers()
})
</script>

<style scoped>
.vip-management {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.vip-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.active-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.revenue-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.conversion-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.main-card {
  background: white;
  border-radius: 8px;
}

.tab-content {
  padding: 0;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.nickname {
  font-size: 14px;
  color: #303133;
}

.expiring-text {
  color: #e6a23c;
  font-weight: 500;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-tabs__header) {
  margin: 0 0 20px 0;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
